package com.polaris.live.ui.live.widget

import android.content.Context
import android.os.CountDownTimer
import android.util.AttributeSet
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.animation.DecelerateInterpolator
import com.blankj.utilcode.util.ColorUtils
import com.blankj.utilcode.util.ScreenUtils
import com.lxj.xpopup.enums.LayoutStatus
import com.lxj.xpopup.widget.PopupDrawerLayout
import com.polaris.live.common.constant.AppConst
import com.polaris.live.common.constant.PagConst.HOME_FREE_CALL_PAG
import com.polaris.live.common.ext.setOnSingleClickListener
import com.polaris.live.constant.LiveConst
import com.polaris.live.constant.LiveConst.CallCloseType
import com.polaris.live.databinding.LayoutLivingCallBinding
import com.polaris.live.im.sfs.bean.live.CallSignalingMessage
import com.polaris.live.popup.WeekStarBlockPopup
import com.polaris.live.utils.RichCharmImgUtil
import com.polaris.live.widget.AnimUtils
import com.polaris.live.widget.avatar.FrameImageUtils
import com.polaris.live.widget.drag.DrawerDragLayout
import com.polaris.live.widget.drag.OnViewDestroyListener
import com.vanniktech.ui.parentViewGroup

/**
 * 直播通话同意功能，一次性的
 *
 * @author Created by lucas on 2023/11/11 09:55
 */
class LiveAnswerItemView(context: Context, attributeSet: AttributeSet? = null) :
    DrawerDragLayout(context, attributeSet) {

    private val mBinding = LayoutLivingCallBinding.inflate(LayoutInflater.from(context), this, true)

    private var mCallAnswerBean: CallSignalingMessage? = null
    private var mCallCountdown: CallTimeoutCountDown? = null//来电话后的15秒定时器

    private var mOnLiveAnswerListener: OnLiveAnswerListener? = null
    private var mOnViewDestroyListener: OnViewDestroyListener? = null

    init {
        onFinishInflate()
        status = LayoutStatus.Open
        setOnCloseListener(object : PopupDrawerLayout.OnCloseListener {
            override fun onClose() {
                outCallWindow()
            }

            override fun onOpen() {
            }

            override fun onDrag(x: Int, fraction: Float, isToLeft: Boolean) {
            }
        })
        super.setOnViewDestroyListener {
            parentViewGroup().apply {
                post {
                    removeView(this@LiveAnswerItemView)
                }
            }

            mOnViewDestroyListener?.onViewDestroy(this)
        }
    }

    /**
     * 来电
     */
    fun onLivingToCall(view: ViewGroup, callBean: CallSignalingMessage) {
        if (mCallAnswerBean != null) {
            return
        }

        mCallAnswerBean = callBean
        if (mCallCountdown == null) {
            mCallCountdown = CallTimeoutCountDown(LiveConst.ANSWER_TIMEOUT, 1000).apply {
                start()
            }
        }

        mBinding.apply {
            userAvatar.setImageUrl(callBean.avatar)
            avFv.setFrameImage(FrameImageUtils.urlToFrameImageBean(callBean.avatarFrame))
            nickName.text = callBean.nickname

            countryImg.setCountry(callBean.country)

            val isMan =
                callBean.sex == AppConst.UserSex.MAN || callBean.sex == AppConst.UserSex.NONE
            val level = if (isMan) {
                callBean.richs.let { RichCharmImgUtil.getLiveRichImg(it) }
            } else {
                callBean.charms.let { RichCharmImgUtil.getLiveCharmImg(it) }
            }

            level.second?.let {
                levelImg.setImageResource(it)
                tvLevel.text = "${level.first}"

                tvLevel.textColorBuilder.textStrokeColor = ColorUtils.getColor(level.third)
                tvLevel.textColorBuilder.intoTextColor()
            }
            pagView.apply {
                path = HOME_FREE_CALL_PAG
                setRepeatCount(-1)
                play()
            }
            ivClose.setOnSingleClickListener {
                WeekStarBlockPopup.showPop(context, callBean.sender) {
                    mOnLiveAnswerListener?.onRefuse(
                        callBean,
                        LiveConst.CloseType.CANCEL
                    )
                    outCallWindow()
                }
            }
            toListener.setOnSingleClickListener {
                mOnLiveAnswerListener?.onAnswer(callBean, true)
                outCallWindow()
            }
            if (callBean.getCallVo()?.starCall == false) {
                starView.visibility = View.GONE
            }
        }

        view.addView(this)

        translationX = ScreenUtils.getScreenWidth().toFloat()

        post {
            if (context.resources.configuration.layoutDirection == View.LAYOUT_DIRECTION_RTL) {
                AnimUtils.inLeft(this, width, {
                    interpolator = DecelerateInterpolator()
                })
            } else {
                AnimUtils.inRight(this, width, {
                    interpolator = DecelerateInterpolator()
                })
            }
        }
    }

    //接听方15倒计时
    private inner class CallTimeoutCountDown(millisInFuture: Long, countDownInterval: Long) :
        CountDownTimer(millisInFuture, countDownInterval) {

        override fun onTick(millisUntilFinished: Long) {}

        override fun onFinish() {
            mCallAnswerBean?.let {
                mOnLiveAnswerListener?.onRefuse(it, LiveConst.CloseType.TIMEOUT)
            }
            outCallWindow()
        }
    }

    //关闭已经结束的view
    fun closeWindowIfEnd(callId: Long) {
        if (callId == mCallAnswerBean?.callId) {
            outCallWindow()
        }
    }

    //移除接听小弹窗
    private fun outCallWindow() {
        mBinding.pagView.pause()

        mCallCountdown?.cancel()
        mCallAnswerBean = null

        close()
    }

    fun setOnLiveAnswerListener(l: OnLiveAnswerListener) {
        mOnLiveAnswerListener = l
    }

    override fun setOnViewDestroyListener(l: OnViewDestroyListener) {
        mOnViewDestroyListener = l
    }

    override fun onDetachedFromWindow() {
        super.onDetachedFromWindow()

        mCallCountdown?.cancel()
        mCallCountdown = null
    }
}

interface OnLiveAnswerListener {

    fun onAnswer(message: CallSignalingMessage, needLoading: Boolean = false)

    fun onRefuse(message: CallSignalingMessage, @CallCloseType type: Int)

}